package com.lifesea.notify.mq.handler;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.lifesea.base.entity.PushAppEnums;
import com.lifesea.base.entity.PushConst;
import com.lifesea.base.entity.PushRequest;
import com.lifesea.commons.cache.RedisConst;
import com.lifesea.commons.mq.entity.MqRequest;
import com.lifesea.commons.utils.PushUtils;
import com.lifesea.notify.service.IPushService;
import com.lifesea.rocketmq.utils.handler.MessageHandler;
import com.lifesea.rocketmq.utils.message.MessageDecoder;
import com.lifesea.rocketmq.utils.message.codec.JsonMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

import javax.annotation.Resource;

/**
 * 就诊提醒消息处理器
 */
@Component
public class BookRemindHandler implements MessageHandler<MqRequest> {

    @Resource
    private IPushService pushService;
    private static final Logger logger = LoggerFactory.getLogger(BookRemindHandler.class);
    @Autowired
    private JedisCluster jedisCluster;

    @Override
    public ConsumeConcurrentlyStatus process(MqRequest data, MessageExt message, ConsumeConcurrentlyContext context) {
        logger.info("[就诊通知]接收,msgId={},notify={}", message.getMsgId(), data);

        try {
            String key = String.format(RedisConst.BOOK_CLINIC_REMIND, data.getBusinessId());
            if (!jedisCluster.exists(key)) {    // 缓存防止重复

                PushRequest pushRequest = new PushRequest();
                pushRequest.setAppcode(PushAppEnums.resident);
                pushRequest.setEcn(data.getEcn());
                pushRequest.setCategory(PushConst.PUSH_GUAHAO_SUCC);
                pushRequest.setBody(data.getContent());
                pushRequest.setRefId(String.valueOf(data.getBusinessId()));

                if (data.getEcn() != null) {
                    PushUtils.send(pushRequest);
                }

                jedisCluster.setex(key, RedisConst.EXPIRY_ONE_DAY, String.valueOf(System.currentTimeMillis()));
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }

        } catch (Exception e) {
            logger.error("[就诊通知]处理失败", e);
        }
        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
    }

    @Override
    public MessageDecoder<MqRequest> getMessageDecoder() {
        return new JsonMessageDecoder<MqRequest>(MqRequest.class);
    }
}
